import { NextResponse } from "next/server";
import { findUserByEmail, createUser } from "@/app/utils/db";
import { hashPassword, signToken, setAuthCookie } from "@/app/utils/auth";

export const runtime = 'nodejs';

export async function POST(request, { params }) {
  try {
    const body = await request.json();
    const { email, password, displayName } = body || {};

    if (!email || !password) {
      return NextResponse.json({ error: "email and password are required" }, { status: 400 });
    }

    const exists = findUserByEmail(email);
    if (exists) {
      return NextResponse.json({ error: "email already registered" }, { status: 409 });
    }

    const passwordHash = await hashPassword(password);
    const user = createUser({ email, passwordHash, displayName });

    const token = signToken({ sub: user.id, email: user.email });
    const res = NextResponse.json({ id: user.id, email: user.email, displayName: user.display_name }, { status: 201 });
    setAuthCookie(res, token);
    return res;
  } catch (e) {
    return NextResponse.json({ error: "invalid request", detail: String(e?.message || e) }, { status: 400 });
  }
}


